package com.sendpo.zjx.sendpo.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.sendpo.zjx.sendpo.BuildConfig;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.Base64;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.shaohui.bottomdialog.BottomDialog;

/**
 * Created by 朱俊鑫 on 2018
 */

public class UpMerchandiseActivity extends AppCompatActivity {
    public final int REQUEST_CAMERA = 104;
    public final int REQUEST_CROP = 105;
    public final int REQUEST_IMAGECOUNT = 1031;

    @BindView(R.id.backbt)
    RelativeLayout backbt;
    @BindView(R.id.head)
    RelativeLayout head;
    @BindView(R.id.bg_iv)
    ImageView bgIv;
    @BindView(R.id.cir_icon)
    ImageView cirIcon;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.camera_bt)
    RelativeLayout cameraBt;
    @BindView(R.id.storetitle_tv)
    TextView storetitleTv;
    @BindView(R.id.realname_edit)
    EditText realnameEdit;
    @BindView(R.id.openmiaoqiang_tv)
    TextView openmiaoqiangTv;
    @BindView(R.id.openmiaoqiang_spinnder)
    Spinner openmiaoqiangSpinnder;
    @BindView(R.id.allowchoujiang_tv)
    TextView allowchoujiangTv;
    @BindView(R.id.allowchoujiang_spinnder)
    Spinner allowchoujiangSpinnder;
    @BindView(R.id.dajianjia_tv)
    TextView dajianjiaTv;
    @BindView(R.id.dajianjia_spinnder)
    Spinner dajianjiaSpinnder;
    @BindView(R.id.buyjifen_tv)
    TextView buyjifenTv;
    @BindView(R.id.buyjifen_edit)
    EditText buyjifenEdit;
    @BindView(R.id.usejifen_tv)
    TextView usejifenTv;
    @BindView(R.id.usejifen_edit)
    EditText usejifenEdit;
    @BindView(R.id.buyjifenmoney_tv)
    TextView buyjifenmoneyTv;
    @BindView(R.id.buyjifenmoney_edit)
    EditText buyjifenmoneyEdit;
    @BindView(R.id.alljifenbuy_tv)
    TextView alljifenbuyTv;
    @BindView(R.id.alljifenbuy_spiner)
    Spinner alljifenbuySpiner;
    @BindView(R.id.pindan_spinner_tv)
    TextView pindanSpinnerTv;
    @BindView(R.id.pindan_spinner)
    Spinner pindanSpinner;
    @BindView(R.id.pindannum_tv)
    TextView pindannumTv;
    @BindView(R.id.pindannum_edit)
    EditText pindannumEdit;
    @BindView(R.id.song_spinner_tv)
    TextView songSpinnerTv;
    @BindView(R.id.song_spinner)
    Spinner songSpinner;
    @BindView(R.id.mianfei_spinner_tv)
    TextView mianfeiSpinnerTv;
    @BindView(R.id.mianfei_spinner)
    Spinner mianfeiSpinner;
    @BindView(R.id.edit_active)
    EditText editActive;
    @BindView(R.id.yuyue_tv)
    TextView yuyueTv;
    @BindView(R.id.yuyue_edit)
    EditText yuyueEdit;
    @BindView(R.id.origin_tv)
    TextView originTv;
    @BindView(R.id.origin_edit)
    EditText originEdit;
    @BindView(R.id.nowprice_tv)
    TextView nowpriceTv;
    @BindView(R.id.nowprice_edit)
    EditText nowpriceEdit;
    @BindView(R.id.peisong_tv)
    TextView peisongTv;
    @BindView(R.id.peisong_edit)
    EditText peisongEdit;
    @BindView(R.id.count_tv)
    TextView countTv;
    @BindView(R.id.count_edit)
    EditText countEdit;
    @BindView(R.id.edit_detail)
    EditText editDetail;
    @BindView(R.id.submitbt)
    Button submitbt;
    public int mianfeitype = 0;
    private Dialog loadingdialog;
    private BottomDialog bottomDialog;
    private File temp_cmera;
      private  int merchantsId=0;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upmerchandise);
        ButterKnife.bind(this);
        Tools.initStatus(this, R.color.black);
        merchantsId=getIntent().getIntExtra("merchantsId",0);
        initComponent();

    }

    private void initComponent() {
        this.loadingdialog = new Dialog(this);
        this.loadingdialog.setContentView(R.layout.dialog_loading);
        this.loadingdialog.setCanceledOnTouchOutside(false);
        this.loadingdialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        bottomDialog = BottomDialog.create(getSupportFragmentManager());
        bottomDialog.setViewListener(new BottomDialog.ViewListener() {
            @Override
            public void bindView(View v) {
                v.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        bottomDialog.dismiss();
                    }
                });
                View camera = v.findViewById(R.id.camera);
                camera.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        temp_cmera = new File(getExternalCacheDir().getAbsolutePath() + "/" + UUID.randomUUID().toString().substring(0, 10) + ".jpg");
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        intent.putExtra("return-data", true);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            Uri contentUri = FileProvider.getUriForFile(UpMerchandiseActivity.this, BuildConfig.APPLICATION_ID + ".fileProvider", temp_cmera);
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
                        } else {
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(temp_cmera));
                        }
                        startActivityForResult(intent, REQUEST_CAMERA);
                        bottomDialog.dismiss();
                    }
                });
                View exit = v.findViewById(R.id.exit);
                exit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        bottomDialog.dismiss();
                    }
                });
                View imgcontent = v.findViewById(R.id.imgcontent);
                imgcontent.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
                        intent.setType("image/*");
                        intent.putExtra("return-data", true);
                        startActivityForResult(intent, REQUEST_IMAGECOUNT);
                        bottomDialog.dismiss();
                    }
                });
            }
        });
        bottomDialog.setLayoutRes(R.layout.dialog_uploadimg);
        bottomDialog.setDimAmount(0.5f);
        bottomDialog.setCancelOutside(true);
        bottomDialog.setTag("BottomDialog");
        mianfeiSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mianfeitype=position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    @OnClick(value = {R.id.backbt, R.id.camera_bt,R.id.submitbt})
    public void onMyClick(View view) {
        switch (view.getId()) {
            case R.id.backbt:
                finish();
                break;
            case R.id.camera_bt:
                       bottomDialog.show();
                break;

            case R.id.submitbt:
              if(temp_cmera==null){
                  Toast.makeText(getApplicationContext(),"请上传商品图片 ",Toast.LENGTH_SHORT).show();
                  return;
              }
              if(TextUtils.isEmpty(realnameEdit.getText().toString().trim())){
                  Toast.makeText(getApplicationContext(),"商品名称不能为空 ",Toast.LENGTH_SHORT).show();
                  return;
              }
              if(TextUtils.isEmpty(originEdit.getText().toString().trim())){
                  Toast.makeText(getApplicationContext(),"原价不允许为空 ",Toast.LENGTH_SHORT).show();
                  return;
              }
                if(TextUtils.isEmpty(nowpriceEdit.getText().toString().trim())){
                    Toast.makeText(getApplicationContext(),"现价不允许为空 ",Toast.LENGTH_SHORT).show();
                    return;
                }
                if(TextUtils.isEmpty(countEdit.getText().toString().trim())){
                    Toast.makeText(getApplicationContext(),"库存不允许为空 ",Toast.LENGTH_SHORT).show();
                    return;
                }

              double origin=0.00;
              double nowprice=0.00;
              double peisongfee=0.00;
              int count=0;
                DecimalFormat decimalFormat=new DecimalFormat("0.00");
              try{
                  origin=Double.parseDouble(originEdit.getText().toString().trim());
              }catch (Exception e){
                  Toast.makeText(getApplicationContext(),"原价不是个数字 ",Toast.LENGTH_SHORT).show();
                  return;
              }
              if(origin<=0.00){
                  Toast.makeText(getApplicationContext(),"原价必须大于0 ",Toast.LENGTH_SHORT).show();
              }
                try{
                    nowprice=Double.parseDouble(nowpriceEdit.getText().toString().trim());
                }catch (Exception e){
                    Toast.makeText(getApplicationContext(),"现价不是个数字 ",Toast.LENGTH_SHORT).show();
                    return;
                }
                try{
                    count=Integer.parseInt(countEdit.getText().toString().trim());
                    if(count<=0){
                        Toast.makeText(getApplicationContext(),"库存不能小于1 ",Toast.LENGTH_SHORT).show();
                       return;
                    }
                }catch (Exception e){
                    Toast.makeText(getApplicationContext(),"库存不是个数字 ",Toast.LENGTH_SHORT).show();
                    return;
                }

                try{
                    peisongfee=Double.parseDouble(peisongEdit.getText().toString().trim());
                }catch (Exception e){
                    Toast.makeText(getApplicationContext(),"配送费不是个数字 ",Toast.LENGTH_SHORT).show();
                    return;
                }
                if(mianfeitype==0){
                    if(nowprice!=0.00){
                        Toast.makeText(getApplicationContext(),"免费商品必须现价为0 ",Toast.LENGTH_SHORT).show();
                  return;
                    }
                }
              JSONObject data=new JSONObject();
                try {
                    data.put("merchantsId",merchantsId);
                    data.put("merchandiseName",realnameEdit.getText().toString().trim());
                    data.put("merchandiseOriginalprice",decimalFormat.format(origin));
                    data.put("merchandiseCurrentprice",decimalFormat.format(nowprice));
                    data.put("merchandiseCount",count);
                    data.put("merchandiseDetails",editDetail.getText().toString().trim());
                    data.put("merchandiseSongtype",songSpinner.getSelectedItemPosition());
                    data.put("activityDetails",editActive.getText().toString().trim());
                    data.put("giveMethod",mianfeitype);
                    data.put("merchandisePeisongfee",decimalFormat.format(peisongfee));
                 JSONArray ja=new JSONArray();
                  ja.put(""+Tools.fileToBase64(temp_cmera));
                 data.put("imgs",ja.toString());
                    submitUp(data);
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(),"上传出错 ",Toast.LENGTH_SHORT).show();
                }

                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        final List<User> userList = Xutils.queryAll(getApplication(), User.class);
        if (userList == null || userList.size() == 0) {
            return;
        }
        switch (requestCode) {
            case REQUEST_IMAGECOUNT:
                Uri datauri = data.getData();
                final File finalFile1 = new File(getExternalCacheDir().getAbsolutePath() + "/" + UUID.randomUUID().toString().substring(0, 10) + ".png");
                ;
                Glide.with(this)
                        .load(datauri)
                        .asBitmap()
                        .override(500, 500)
                        .placeholder(getResources().getColor(R.color.default_lightgray))
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                try {
                                    Bitmap bitmap = null;
                                    if (resource.getHeight() < 500) {
                                        bitmap = Tools.zoomBitmap(resource, resource.getWidth() / 1, resource.getHeight() / 1);
                                    } else if (resource.getHeight() < 1000) {
                                        bitmap = Tools.zoomBitmap(resource, resource.getWidth() / 2, resource.getHeight() / 2);
                                    } else {
                                        bitmap = Tools.zoomBitmap(resource, resource.getWidth() / 3, resource.getHeight() / 3);
                                    }
                                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(finalFile1));
                                    temp_cmera=finalFile1;
                                    bgIv.setImageBitmap(bitmap);
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                }
                            }
                        });

                break;

            case REQUEST_CAMERA:
                Intent bgcamera = new Intent("com.android.camera.action.CROP");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    bgcamera.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri contentUri = FileProvider.getUriForFile(UpMerchandiseActivity.this, BuildConfig.APPLICATION_ID + ".fileProvider", temp_cmera);
                    bgcamera.setDataAndType(contentUri, "image/*");
                } else {
                    bgcamera.setDataAndType(Uri.fromFile(temp_cmera), "image/*");
                }
                bgcamera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(temp_cmera));
                bgcamera.putExtra("return-data", false);
                bgcamera.putExtra("scale", true);
                bgcamera.putExtra("outputFormat", Bitmap.CompressFormat.PNG);
                bgcamera.putExtra("noFaceDetection", true);
//                bgcamera.putExtra("aspectX", 1);
//                bgcamera.putExtra("aspectY", 1);
                bgcamera.putExtra("outputX", 500);
                bgcamera.putExtra("outputY", 500);
                startActivityForResult(bgcamera, REQUEST_CROP);
                break;
            case REQUEST_CROP:
                Glide.with(this)
                        .load(temp_cmera.getPath())
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                Bitmap bitmap = null;
                                if (resource.getHeight() < 500) {
                                    bitmap = Tools.zoomBitmap(resource, resource.getWidth() / 1, resource.getHeight() / 1);
                                } else if (resource.getHeight() < 1000) {
                                    bitmap = Tools.zoomBitmap(resource, resource.getWidth() / 2, resource.getHeight() / 2);
                                } else {
                                    bitmap = Tools.zoomBitmap(resource, resource.getWidth() / 3, resource.getHeight() / 3);
                                }
                                try {
                                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(temp_cmera));
                                    bgIv.setImageBitmap(bitmap);
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                }
                            }
                        });

                break;

        }
    }


    public void submitUp(JSONObject jsonObject){
        loadingdialog.show();
        System.out.println("**********************************"+jsonObject.toString());
        RequestParams requestParams=new RequestParams(HttpUrl.addProduct);
        requestParams.setMultipart(true);
        requestParams.setAsJsonContent(true);
        requestParams.setBodyContent(jsonObject.toString());
        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                loadingdialog.dismiss();
                try {
                    JSONObject data=new JSONObject(result);
                  if (data.getBoolean("flag")){
                     Toast.makeText(getApplicationContext(),"上架成功",Toast.LENGTH_SHORT).show();
                        finish();
                    }else{
                      Toast.makeText(getApplicationContext(),"上架失败",Toast.LENGTH_SHORT).show();
                  }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                loadingdialog.dismiss();
                Toast.makeText(getApplicationContext(),"请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}

